import React, { useState, useEffect, useMemo, useCallback, useRef } from "react";
import {
  Modal,
  Typography,
  Space,
  Tag,
  Progress,
  Card,
  List,
  Button,
  Divider,
  Row,
  Col,
  Statistic,
  Alert,
  Collapse,
  Avatar,
  Spin,
  message,
} from "antd";
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  FileTextOutlined,
  TrophyOutlined,
  BookOutlined,
  EyeOutlined,
  CheckOutlined,
  CloseOutlined,
  QuestionCircleOutlined,
  RobotOutlined,
  ThunderboltOutlined,
  BulbOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import { AIService } from "../../../../services/ai";
import { useExamContext } from "../../../../contexts/ExamContext";

const { Title, Text, Paragraph } = Typography;
const { Panel } = Collapse;

// 样式组件
const StyledModal = styled(Modal)`
  .ant-modal-body {
    max-height: 80vh;
    overflow-y: auto;
  }
`;

const StatsCard = styled(Card)`
  margin-bottom: 16px;
  .ant-card-body {
    padding: 16px;
  }
`;

const QuestionCard = styled(Card)`
  margin-bottom: 16px;
  border-left: 4px solid #d9d9d9;
  
  &.correct {
    border-left-color: #52c41a;
  }
  
  &.incorrect {
    border-left-color: #ff4d4f;
  }
  
  &.partial {
    border-left-color: #faad14;
  }
`;

const AnswerSection = styled.div`
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  margin-top: 8px;
`;

const ExplanationSection = styled.div`
  background: #e6f7ff;
  padding: 12px;
  border-radius: 6px;
  margin-top: 8px;
  border-left: 3px solid #1890ff;
`;

const AIExplanationSection = styled.div`
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 16px;
  border-radius: 8px;
  margin-top: 12px;
  color: white;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.1);
    transform: rotate(45deg);
  }
`;

interface Question {
  id: string;
  type: "single" | "multiple" | "essay" | "judge" | "fill";
  question: string;
  options?: string[];
  userAnswer: any;
  correctAnswer: any;
  score: number;
  fullScore: number;
  explanation: string;
  section: string;
  knowledgePoint?: string;
  aiExplanation?: string;
}

interface ExamDetail {
  id: string;
  title: string;
  course: string;
  time: string;
  duration: string;
  score: number;
  fullScore: number;
  questions: Question[];
  totalQuestions: number;
  correctQuestions: number;
  accuracy: number;
  timeSpent: string;
  submittedAt: string;
}

interface ExamDetailModalProps {
  visible: boolean;
  examId: string;
  onClose: () => void;
}

// 根据考试ID生成对应的题目模板
const generateExamQuestions = (examId: string): Question[] => {
  const questionTemplates = {
    "1": { // 数据结构期中考试
      course: "数据结构与算法",
      knowledgePoints: ["线性表", "栈和队列", "树结构", "图算法", "排序算法"],
      questions: [
        {
          id: "1",
          type: "single" as const,
          section: "线性表",
          knowledgePoint: "线性表",
          question: "下列关于线性表的描述，正确的是？",
          options: [
            "线性表中的元素可以是不同类型的数据",
            "线性表只能顺序存储，不能链式存储",
            "线性表中的元素具有唯一的前驱和后继",
            "线性表是一种非线性数据结构"
          ],
          userAnswer: 0,
          correctAnswer: 0,
          score: 5,
          fullScore: 5,
          explanation: "线性表是最基本的数据结构，其中的元素具有唯一的前驱和后继关系。选项C正确描述了线性表的基本特征。"
        },
        {
          id: "2",
          type: "single" as const,
          section: "栈和队列",
          knowledgePoint: "栈和队列",
          question: "栈的特点是？",
          options: [
            "先进先出（FIFO）",
            "后进先出（LIFO）",
            "随机存取",
            "双向存取"
          ],
          userAnswer: 1,
          correctAnswer: 1,
          score: 5,
          fullScore: 5,
          explanation: "栈是一种后进先出（LIFO）的数据结构，最后入栈的元素最先出栈。"
        },
        {
          id: "3",
          type: "fill" as const,
          section: "树结构",
          knowledgePoint: "树结构",
          question: "二叉树中，度为2的节点称为____节点。",
          userAnswer: "分支",
          correctAnswer: "分支",
          score: 3,
          fullScore: 3,
          explanation: "在二叉树中，度为2的节点称为分支节点，度为0的节点称为叶子节点。"
        },
        {
          id: "4",
          type: "essay" as const,
          section: "图算法",
          knowledgePoint: "图算法",
          question: "请简述深度优先搜索（DFS）和广度优先搜索（BFS）的区别，并说明它们各自的应用场景。",
          userAnswer: "DFS使用栈结构，沿着一条路径一直搜索到底，然后回溯；BFS使用队列结构，逐层搜索。DFS适用于需要深入探索的场景，BFS适用于寻找最短路径。",
          correctAnswer: "DFS使用栈结构，沿着一条路径一直搜索到底，然后回溯；BFS使用队列结构，逐层搜索。DFS适用于需要深入探索的场景，BFS适用于寻找最短路径。",
          score: 15,
          fullScore: 15,
          explanation: "您的回答准确描述了DFS和BFS的核心区别。DFS适合解决迷宫问题、拓扑排序等；BFS适合解决最短路径、层次遍历等问题。"
        },
        {
          id: "5",
          type: "multiple" as const,
          section: "排序算法",
          knowledgePoint: "排序算法",
          question: "以下哪些排序算法的时间复杂度为O(nlogn)？",
          options: [
            "快速排序",
            "归并排序",
            "堆排序",
            "冒泡排序"
          ],
          userAnswer: [0, 1, 2],
          correctAnswer: [0, 1, 2],
          score: 8,
          fullScore: 8,
          explanation: "快速排序、归并排序、堆排序的平均时间复杂度都是O(nlogn)，而冒泡排序的时间复杂度是O(n²)。"
        }
      ]
    },
    "2": { // 数据库系统期末考试
      course: "数据库系统原理",
      knowledgePoints: ["关系数据库", "SQL语言", "数据库设计", "事务管理", "查询优化"],
      questions: [
        {
          id: "1",
          type: "single" as const,
          section: "关系数据库",
          knowledgePoint: "关系数据库",
          question: "关系数据库的三大范式不包括？",
          options: [
            "第一范式（1NF）",
            "第二范式（2NF）",
            "第三范式（3NF）",
            "第四范式（4NF）"
          ],
          userAnswer: 3,
          correctAnswer: 3,
          score: 5,
          fullScore: 5,
          explanation: "关系数据库的三大范式是第一范式（1NF）、第二范式（2NF）和第三范式（3NF）。第四范式（4NF）是更高级的范式。"
        },
        {
          id: "2",
          type: "fill" as const,
          section: "SQL语言",
          knowledgePoint: "SQL语言",
          question: "SQL中用于查询数据的关键字是____。",
          userAnswer: "SELECT",
          correctAnswer: "SELECT",
          score: 3,
          fullScore: 3,
          explanation: "SELECT是SQL中用于查询数据的关键字，用于从数据库中检索数据。"
        },
        {
          id: "3",
          type: "essay" as const,
          section: "数据库设计",
          knowledgePoint: "数据库设计",
          question: "请说明数据库设计中的概念设计、逻辑设计和物理设计的主要内容。",
          userAnswer: "概念设计主要确定实体、属性和关系；逻辑设计将概念模型转换为关系模型；物理设计确定存储结构和索引策略。",
          correctAnswer: "概念设计主要确定实体、属性和关系；逻辑设计将概念模型转换为关系模型；物理设计确定存储结构和索引策略。",
          score: 15,
          fullScore: 15,
          explanation: "您的回答准确概括了数据库设计的三个层次。概念设计关注用户需求，逻辑设计关注数据模型，物理设计关注性能优化。"
        },
        {
          id: "4",
          type: "judge" as const,
          section: "事务管理",
          knowledgePoint: "事务管理",
          question: "事务的ACID特性中，A代表原子性（Atomicity）。",
          userAnswer: true,
          correctAnswer: true,
          score: 5,
          fullScore: 5,
          explanation: "ACID特性中的A确实代表原子性（Atomicity），表示事务是不可分割的工作单位。"
        },
        {
          id: "5",
          type: "multiple" as const,
          section: "查询优化",
          knowledgePoint: "查询优化",
          question: "以下哪些是查询优化的常用技术？",
          options: [
            "索引优化",
            "查询重写",
            "统计信息",
            "并行处理"
          ],
          userAnswer: [0, 1, 2, 3],
          correctAnswer: [0, 1, 2, 3],
          score: 8,
          fullScore: 8,
          explanation: "这些都是查询优化的常用技术。索引优化提高查询速度，查询重写简化查询逻辑，统计信息帮助优化器选择执行计划，并行处理提高查询效率。"
        }
      ]
    },
    "3": { // 计算机网络实验考核
          course: "计算机网络",
      knowledgePoints: ["网络协议", "网络配置", "网络编程", "协议分析"],
          questions: [
            {
              id: "1",
          type: "single" as const,
          section: "网络协议",
          knowledgePoint: "网络协议",
          question: "TCP协议属于OSI七层模型中的哪一层？",
          options: [
            "物理层",
            "数据链路层",
            "网络层",
            "传输层"
          ],
          userAnswer: 3,
          correctAnswer: 3,
          score: 5,
          fullScore: 5,
          explanation: "TCP（传输控制协议）属于OSI七层模型中的传输层，负责端到端的可靠数据传输。"
        },
        {
          id: "2",
          type: "fill" as const,
          section: "网络配置",
          knowledgePoint: "网络配置",
          question: "IPv4地址由____位二进制数组成。",
          userAnswer: "32",
          correctAnswer: "32",
          score: 3,
          fullScore: 3,
          explanation: "IPv4地址由32位二进制数组成，通常表示为4个8位字节，用点分十进制表示。"
        },
        {
          id: "3",
          type: "essay" as const,
          section: "网络编程",
          knowledgePoint: "网络编程",
          question: "请编写一个简单的TCP客户端程序，实现与服务器的连接和数据传输。",
          userAnswer: "使用socket()创建套接字，connect()连接服务器，send()发送数据，recv()接收数据，close()关闭连接。",
          correctAnswer: "使用socket()创建套接字，connect()连接服务器，send()发送数据，recv()接收数据，close()关闭连接。",
          score: 20,
          fullScore: 20,
          explanation: "您的回答概括了TCP客户端的基本流程。具体实现需要包含错误处理、数据格式化和连接状态管理。"
        },
        {
          id: "4",
          type: "judge" as const,
          section: "协议分析",
          knowledgePoint: "协议分析",
          question: "HTTP协议是无状态协议。",
          userAnswer: true,
          correctAnswer: true,
          score: 5,
          fullScore: 5,
          explanation: "HTTP协议确实是无状态协议，每个请求都是独立的，服务器不会保存客户端的状态信息。"
        }
      ]
    },
    "4": { // 计算机网络期中考试
      course: "计算机网络",
      knowledgePoints: ["网络基础", "TCP/IP协议", "网络层", "传输层"],
      questions: [
        {
          id: "1",
          type: "single" as const,
          section: "网络基础",
          knowledgePoint: "网络基础",
          question: "计算机网络的主要功能不包括？",
          options: [
            "资源共享",
            "信息传输",
            "分布式处理",
            "硬件制造"
          ],
          userAnswer: 3,
          correctAnswer: 3,
          score: 5,
          fullScore: 5,
          explanation: "计算机网络的主要功能包括资源共享、信息传输、分布式处理等，但不包括硬件制造。"
        },
        {
          id: "2",
          type: "fill" as const,
          section: "TCP/IP协议",
          knowledgePoint: "TCP/IP协议",
          question: "TCP/IP协议栈中，IP协议位于____层。",
          userAnswer: "网络",
          correctAnswer: "网络",
          score: 3,
          fullScore: 3,
          explanation: "在TCP/IP协议栈中，IP协议位于网络层，负责数据包的路由和转发。"
        },
        {
          id: "3",
          type: "essay" as const,
          section: "网络层",
          knowledgePoint: "网络层",
          question: "请解释IP地址的分类和子网掩码的作用。",
          userAnswer: "IP地址分为A、B、C、D、E五类，子网掩码用于划分网络地址和主机地址，实现子网划分。",
          correctAnswer: "IP地址分为A、B、C、D、E五类，子网掩码用于划分网络地址和主机地址，实现子网划分。",
          score: 15,
          fullScore: 15,
          explanation: "您的回答正确。A类地址范围1-126，B类128-191，C类192-223。子网掩码通过位运算确定网络部分和主机部分。"
        },
        {
          id: "4",
          type: "judge" as const,
          section: "传输层",
          knowledgePoint: "传输层",
          question: "UDP协议提供可靠的数据传输服务。",
          userAnswer: false,
          correctAnswer: false,
          score: 5,
          fullScore: 5,
          explanation: "UDP协议是无连接的传输协议，不提供可靠的数据传输服务，数据可能丢失、重复或乱序。"
        }
      ]
    },
    "5": { // 计算机组成原理期中考试
      course: "计算机组成原理",
      knowledgePoints: ["CPU结构", "存储器", "指令系统", "总线系统"],
      questions: [
        {
          id: "1",
          type: "single" as const,
          section: "CPU结构",
          knowledgePoint: "CPU结构",
          question: "CPU的主要组成部分不包括？",
          options: [
            "运算器",
            "控制器",
            "存储器",
            "显示器"
          ],
          userAnswer: 3,
          correctAnswer: 3,
          score: 5,
          fullScore: 5,
          explanation: "CPU的主要组成部分包括运算器、控制器和寄存器组，但不包括显示器。"
        },
        {
          id: "2",
          type: "fill" as const,
          section: "存储器",
          knowledgePoint: "存储器",
          question: "计算机的存储层次结构中，速度最快的是____存储器。",
          userAnswer: "缓存",
          correctAnswer: "缓存",
          score: 3,
          fullScore: 3,
          explanation: "在存储层次结构中，缓存（Cache）的速度最快，但容量最小。"
        },
        {
          id: "3",
          type: "essay" as const,
          section: "指令系统",
          knowledgePoint: "指令系统",
          question: "请说明指令周期的基本步骤。",
          userAnswer: "指令周期包括取指令、译码、执行、访存、写回等步骤，形成指令执行的完整流程。",
          correctAnswer: "指令周期包括取指令、译码、执行、访存、写回等步骤，形成指令执行的完整流程。",
          score: 15,
          fullScore: 15,
          explanation: "您的回答正确。指令周期是CPU执行一条指令的完整过程，不同指令的具体步骤可能有所不同。"
        },
        {
          id: "4",
          type: "judge" as const,
          section: "总线系统",
          knowledgePoint: "总线系统",
          question: "总线是计算机各部件之间传输信息的公共通道。",
          userAnswer: true,
          correctAnswer: true,
          score: 5,
          fullScore: 5,
          explanation: "总线确实是计算机各部件之间传输信息的公共通道，包括数据总线、地址总线和控制总线。"
        }
      ]
    },
    "6": { // 操作系统原理期中考试
      course: "操作系统原理",
      knowledgePoints: ["进程管理", "内存管理", "文件系统", "设备管理"],
      questions: [
        {
          id: "1",
          type: "single" as const,
          section: "进程管理",
          knowledgePoint: "进程管理",
              question: "下列关于操作系统的描述，正确的是？",
              options: [
                "操作系统是计算机系统中最重要的应用软件",
                "操作系统负责管理计算机的硬件和软件资源",
                "操作系统只能管理硬件资源",
            "操作系统不能提供用户接口"
              ],
              userAnswer: 1,
              correctAnswer: 1,
              score: 5,
              fullScore: 5,
          explanation: "操作系统是系统软件，负责管理计算机的硬件和软件资源，为用户和应用程序提供接口和服务。"
            },
            {
              id: "2",
          type: "multiple" as const,
          section: "内存管理",
          knowledgePoint: "内存管理",
              question: "下列属于进程状态的有：",
              options: ["就绪态", "运行态", "阻塞态", "结束态"],
          userAnswer: [0, 1, 2, 3],
              correctAnswer: [0, 1, 2, 3],
          score: 8,
              fullScore: 8,
          explanation: "进程的基本状态包括：就绪态（Ready）、运行态（Running）、阻塞态（Blocked）、结束态（Terminated）。"
            },
            {
              id: "3",
          type: "judge" as const,
          section: "文件系统",
          knowledgePoint: "文件系统",
              question: "虚拟内存技术可以使程序的逻辑地址空间大于物理内存空间。",
              userAnswer: true,
              correctAnswer: true,
          score: 5,
          fullScore: 5,
          explanation: "虚拟内存技术通过将程序的一部分存储在磁盘上，实现了逻辑地址空间大于物理内存空间的效果。"
            },
            {
              id: "4",
          type: "essay" as const,
          section: "设备管理",
          knowledgePoint: "设备管理",
          question: "请简述进程和线程的区别，并说明它们各自的特点和应用场景。",
          userAnswer: "进程是程序的一次执行过程，是系统进行资源分配和调度的基本单位。线程是进程内的一个执行单元，是CPU调度和分派的基本单位。进程拥有独立的内存空间，线程共享所属进程的内存空间。",
          correctAnswer: "进程是程序的一次执行过程，是系统进行资源分配和调度的基本单位。线程是进程内的一个执行单元，是CPU调度和分派的基本单位。进程拥有独立的内存空间，线程共享所属进程的内存空间。",
              score: 12,
              fullScore: 15,
          explanation: "您的回答基本正确，涵盖了进程和线程的主要区别。但在应用场景方面可以更详细：进程适用于需要隔离性的场景，如浏览器多标签页；线程适用于需要共享数据的场景，如多线程下载。"
        }
      ]
    }
  };

  const template = questionTemplates[examId as keyof typeof questionTemplates];
  if (!template) {
    // 默认模板
    return [
      {
        id: "1",
        type: "single" as const,
        section: "基础知识",
        question: "这是一道默认的选择题？",
        options: ["选项A", "选项B", "选项C", "选项D"],
              userAnswer: 0,
              correctAnswer: 0,
        score: 5,
        fullScore: 5,
        explanation: "这是默认题目的解释。"
      }
    ];
  }

  return template.questions;
};

const ExamDetailModal: React.FC<ExamDetailModalProps> = ({
  visible,
  examId,
  onClose,
}) => {
  const [loading, setLoading] = useState(false);
  const [examDetail, setExamDetail] = useState<ExamDetail | null>(null);
  const [aiLoadingStates, setAiLoadingStates] = useState<Record<string, boolean>>({});
  const aiService = new AIService();
  const { getExamById, exams } = useExamContext();
  const examDetailRef = useRef<ExamDetail | null>(null);

  // 使用useMemo缓存生成的答案，避免每次重新渲染时都生成新的随机答案
  const cachedExamDetail = useMemo(() => {
    if (!examId) return null;
    
    // 使用固定的考试信息，避免依赖context中的不稳定数据
    const examInfo = {
      "1": { title: "数据结构期中考试", course: "数据结构与算法", time: "2024-12-26 14:00", duration: 120, submittedAt: "2024-12-26 15:38" },
      "2": { title: "数据库系统期末考试", course: "数据库系统原理", time: "2025-01-15 09:00", duration: 120, submittedAt: "2025-01-15 10:25" },
      "3": { title: "计算机网络实验考核", course: "计算机网络", time: "2025-01-10 14:00", duration: 90, submittedAt: "2025-01-10 15:15" },
      "4": { title: "操作系统原理考试", course: "操作系统原理", time: "2024-12-20 14:00", duration: 120, submittedAt: "2024-12-20 15:30" },
      "5": { title: "软件工程综合测试", course: "软件工程", time: "2024-12-15 09:00", duration: 150, submittedAt: "2024-12-15 11:20" }
    };
    
    const exam = examInfo[examId as keyof typeof examInfo] || {
      title: "默认考试",
      course: "默认课程", 
      time: "2024-12-20 14:00",
      duration: 120,
      submittedAt: "2024-12-20 15:38"
    };
    
    const questions = generateExamQuestions(examId);
    
    // 使用examId作为种子生成固定的随机答案
    const seed = examId.split('').reduce((a, b) => a + b.charCodeAt(0), 0);
    const seededRandom = (min: number, max: number) => {
      const x = Math.sin(seed) * 10000;
      return Math.floor((x - Math.floor(x)) * (max - min + 1)) + min;
    };
    
    // 生成固定的学生答案
    const mockUserAnswers = questions.map((q, index) => {
      if (q.type === "single") {
        return seededRandom(0, (q.options?.length || 1) - 1);
      } else if (q.type === "multiple") {
        const count = seededRandom(1, q.options?.length || 1);
        return Array.from({ length: count }, (_, i) => i).slice(0, count);
      } else if (q.type === "judge") {
        return seededRandom(0, 1) === 1;
      } else if (q.type === "fill") {
        return q.correctAnswer;
      } else {
        return q.correctAnswer;
      }
    });

    // 计算得分
    const totalScore = questions.reduce((sum, q) => sum + q.fullScore, 0);
    const actualScore = questions.reduce((sum, q, index) => {
      const userAnswer = mockUserAnswers[index];
      if (q.type === "single" || q.type === "judge" || q.type === "fill") {
        return sum + (userAnswer === q.correctAnswer ? q.fullScore : 0);
      } else if (q.type === "multiple") {
        const correctCount = q.correctAnswer.length;
        const userCount = userAnswer.length;
        const matchCount = userAnswer.filter((a: any) => q.correctAnswer.includes(a)).length;
        return sum + Math.round((matchCount / correctCount) * q.fullScore);
      } else {
        return sum + Math.round(q.fullScore * 0.8); // 简答题给80%分数
      }
    }, 0);

    const correctQuestions = questions.filter((q, index) => {
      const userAnswer = mockUserAnswers[index];
      if (q.type === "single" || q.type === "judge" || q.type === "fill") {
        return userAnswer === q.correctAnswer;
      } else if (q.type === "multiple") {
        return JSON.stringify(userAnswer.sort()) === JSON.stringify(q.correctAnswer.sort());
      } else {
        return true; // 简答题默认算正确
      }
    }).length;

    return {
      id: examId,
      title: exam.title,
      course: exam.course,
      time: exam.time,
      duration: `${exam.duration}分钟`,
      score: actualScore,
      fullScore: totalScore,
      totalQuestions: questions.length,
      correctQuestions: correctQuestions,
      accuracy: Math.round((correctQuestions / questions.length) * 100),
      timeSpent: `${seededRandom(60, 90)}分钟`,
      submittedAt: exam.submittedAt,
      questions: questions.map((q, index) => ({
        ...q,
        userAnswer: mockUserAnswers[index],
        score: (() => {
          const userAnswer = mockUserAnswers[index];
          if (q.type === "single" || q.type === "judge" || q.type === "fill") {
            return userAnswer === q.correctAnswer ? q.fullScore : 0;
          } else if (q.type === "multiple") {
            const correctCount = q.correctAnswer.length;
            const matchCount = userAnswer.filter((a: any) => q.correctAnswer.includes(a)).length;
            return Math.round((matchCount / correctCount) * q.fullScore);
          } else {
            return Math.round(q.fullScore * 0.8);
          }
        })()
      }))
    };
  }, [examId]); // 只依赖examId，确保稳定性

  // 获取考试详情数据
  const loadExamDetail = useCallback(() => {
    if (visible && examId) {
      setLoading(true);
      
      // 模拟API调用延迟
      setTimeout(() => {
        const detail = cachedExamDetail;
        setExamDetail(detail);
        examDetailRef.current = detail;
        setLoading(false);
      }, 1000);
    }
  }, [visible, examId, cachedExamDetail]);

  useEffect(() => {
    loadExamDetail();
  }, [loadExamDetail]);

  // 清理函数
  useEffect(() => {
    if (!visible) {
      // 关闭模态框时清空数据
      setExamDetail(null);
      examDetailRef.current = null;
      setAiLoadingStates({});
    }
  }, [visible]);

  // 获取AI解析
  const handleGetAIExplanation = useCallback(async (questionId: string, question: Question, isRegenerate: boolean = false) => {
    setAiLoadingStates(prev => ({ ...prev, [questionId]: true }));
    
    try {
      // 构建AI解析请求
      const userAnswer = renderUserAnswer(question);
      const correctAnswer = renderCorrectAnswer(question);
      
      // 模拟AI解析（实际项目中应该调用真实的AI接口）
      const mockAIExplanation = `## AI深度解析

### 题目分析
这是一道关于${question.section}的${question.type === 'single' ? '单选题' : question.type === 'multiple' ? '多选题' : question.type === 'judge' ? '判断题' : question.type === 'fill' ? '填空题' : '简答题'}。

### 知识点回顾
${question.knowledgePoint ? `**${question.knowledgePoint}**：` : ''}${question.explanation}

### 答题情况分析
- **您的答案**：${userAnswer}
- **正确答案**：${correctAnswer}
- **得分情况**：${question.score}/${question.fullScore}分

### 详细解析
${question.explanation}

### 学习建议
1. 深入理解${question.section}的基本概念
2. 多做相关练习题巩固知识点
3. 注意区分易混淆的概念
4. 结合实际应用场景加深理解

### 相关知识点
- ${question.section}的基本原理
- ${question.section}的应用场景
- ${question.section}的发展趋势

希望这个解析对您有帮助！如果还有疑问，建议查阅相关教材或咨询老师。`;

      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 2000));

      // 更新题目数据，添加AI解析
      setExamDetail(prev => {
        if (!prev) return prev;
        
        const updatedQuestions = prev.questions.map(q => 
          q.id === questionId 
            ? { ...q, aiExplanation: mockAIExplanation }
            : q
        );
        
        const updatedDetail = {
          ...prev,
          questions: updatedQuestions
        };
        
        // 同时更新ref
        examDetailRef.current = updatedDetail;
        
        return updatedDetail;
      });
      
      message.success(isRegenerate ? "AI解析重新生成成功！" : "AI解析生成成功！");
    } catch (error) {
      console.error("获取AI解析失败:", error);
      message.error("获取AI解析失败，请稍后重试");
    } finally {
      setAiLoadingStates(prev => ({ ...prev, [questionId]: false }));
    }
  }, [examId]);

  // 判断题目是否正确
  const isQuestionCorrect = (question: Question) => {
    if (question.type === "multiple") {
      return JSON.stringify(question.userAnswer.sort()) === JSON.stringify(question.correctAnswer.sort());
    }
    return question.userAnswer === question.correctAnswer;
  };

  // 判断题目是否部分正确
  const isQuestionPartial = (question: Question) => {
    if (question.type === "multiple") {
      const userSet = new Set(question.userAnswer);
      const correctSet = new Set(question.correctAnswer);
      return userSet.size > 0 && userSet.size < correctSet.size;
    }
    if (question.type === "essay") {
      return question.score > 0 && question.score < question.fullScore;
    }
    return false;
  };

  // 获取题目状态类名
  const getQuestionStatusClass = (question: Question) => {
    if (isQuestionCorrect(question)) return "correct";
    if (isQuestionPartial(question)) return "partial";
    return "incorrect";
  };

  // 获取题目状态图标
  const getQuestionStatusIcon = (question: Question) => {
    if (isQuestionCorrect(question)) {
      return <CheckCircleOutlined style={{ color: "#52c41a" }} />;
    }
    if (isQuestionPartial(question)) {
      return <QuestionCircleOutlined style={{ color: "#faad14" }} />;
    }
    return <CloseCircleOutlined style={{ color: "#ff4d4f" }} />;
  };

  // 渲染选项
  const renderOptions = (question: Question) => {
    if (!question.options) return null;

    return (
      <div style={{ marginTop: 8 }}>
        {question.options.map((option, index) => {
          const isUserAnswer = Array.isArray(question.userAnswer) 
            ? question.userAnswer.includes(index)
            : question.userAnswer === index;
          const isCorrectAnswer = Array.isArray(question.correctAnswer)
            ? question.correctAnswer.includes(index)
            : question.correctAnswer === index;
          
          let style: React.CSSProperties = { padding: "4px 8px", margin: "2px", borderRadius: "4px" };
          
          if (isUserAnswer && isCorrectAnswer) {
            style = { ...style, backgroundColor: "#f6ffed", border: "1px solid #b7eb8f", color: "#52c41a" };
          } else if (isUserAnswer && !isCorrectAnswer) {
            style = { ...style, backgroundColor: "#fff2f0", border: "1px solid #ffccc7", color: "#ff4d4f" };
          } else if (!isUserAnswer && isCorrectAnswer) {
            style = { ...style, backgroundColor: "#f6ffed", border: "1px solid #b7eb8f", color: "#52c41a" };
          }
          
          return (
            <div key={index} style={style}>
              {String.fromCharCode(65 + index)}. {option}
              {isUserAnswer && isCorrectAnswer && <CheckOutlined style={{ marginLeft: 8 }} />}
              {isUserAnswer && !isCorrectAnswer && <CloseOutlined style={{ marginLeft: 8 }} />}
              {!isUserAnswer && isCorrectAnswer && <CheckOutlined style={{ marginLeft: 8 }} />}
            </div>
          );
        })}
      </div>
    );
  };

  // 渲染用户答案
  const renderUserAnswer = (question: Question) => {
    if (question.type === "single") {
      return question.options?.[question.userAnswer] || "未作答";
    }
    if (question.type === "multiple") {
      return question.userAnswer.map((index: number) => question.options?.[index]).join(", ") || "未作答";
    }
    if (question.type === "judge") {
      return question.userAnswer ? "正确" : "错误";
    }
    if (question.type === "essay") {
      return question.userAnswer || "未作答";
    }
    if (question.type === "fill") {
      return question.userAnswer || "未作答";
    }
    return "未作答";
  };

  // 渲染正确答案
  const renderCorrectAnswer = (question: Question) => {
    if (question.type === "single") {
      return question.options?.[question.correctAnswer] || "";
    }
    if (question.type === "multiple") {
      return question.correctAnswer.map((index: number) => question.options?.[index]).join(", ");
    }
    if (question.type === "judge") {
      return question.correctAnswer ? "正确" : "错误";
    }
    if (question.type === "essay") {
      return question.correctAnswer || "";
    }
    if (question.type === "fill") {
      return question.correctAnswer || "";
    }
    return "";
  };

  return (
    <StyledModal
      title={
        <Space>
          <BookOutlined />
          考试详情 - {examDetail?.title || "加载中..."}
        </Space>
      }
      open={visible}
      onCancel={onClose}
      footer={[
        <Button key="close" onClick={onClose}>
          关闭
        </Button>,
      ]}
      width={900}
    >
      {loading ? (
        <div style={{ textAlign: "center", padding: "40px" }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>正在加载考试详情...</div>
        </div>
      ) : examDetail ? (
        <>
      {/* 考试基本信息 */}
      <StatsCard>
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="总分"
              value={examDetail.score}
              suffix={`/ ${examDetail.fullScore}`}
              valueStyle={{ color: "#1890ff" }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="正确率"
              value={examDetail.accuracy}
              suffix="%"
              valueStyle={{ color: "#52c41a" }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="答题时间"
              value={examDetail.timeSpent}
              valueStyle={{ color: "#722ed1" }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="提交时间"
              value={examDetail.submittedAt}
              valueStyle={{ color: "#8c8c8c" }}
            />
          </Col>
        </Row>
      </StatsCard>

      {/* 答题统计 */}
      <StatsCard>
        <Row gutter={16}>
          <Col span={8}>
            <div style={{ textAlign: "center" }}>
              <Progress
                type="circle"
                percent={examDetail.accuracy}
                format={(percent) => `${percent}%`}
                strokeColor="#52c41a"
              />
              <div style={{ marginTop: 8 }}>
                <Text strong>总体正确率</Text>
              </div>
            </div>
          </Col>
          <Col span={8}>
            <div style={{ textAlign: "center" }}>
              <div style={{ fontSize: "24px", fontWeight: "bold", color: "#52c41a" }}>
                {examDetail.correctQuestions}/{examDetail.totalQuestions}
              </div>
              <div style={{ marginTop: 8 }}>
                    <Text strong>正确题数</Text>
              </div>
            </div>
          </Col>
          <Col span={8}>
            <div style={{ textAlign: "center" }}>
              <div style={{ fontSize: "24px", fontWeight: "bold", color: "#1890ff" }}>
                    {examDetail.score}
              </div>
              <div style={{ marginTop: 8 }}>
                    <Text strong>总得分</Text>
              </div>
            </div>
          </Col>
        </Row>
      </StatsCard>

      {/* 题目详情 */}
      <div style={{ marginTop: 16 }}>
        <Title level={4}>
          <EyeOutlined /> 题目详情与解析
        </Title>
        
        <List
          dataSource={examDetail.questions}
          renderItem={(question, index) => (
            <QuestionCard
              key={question.id}
              className={getQuestionStatusClass(question)}
              title={
                <Space>
                  {getQuestionStatusIcon(question)}
                  <Text strong>第{index + 1}题</Text>
                  <Tag color="blue">{question.section}</Tag>
                      {question.knowledgePoint && (
                        <Tag color="purple">{question.knowledgePoint}</Tag>
                      )}
                  <Tag color={isQuestionCorrect(question) ? "success" : isQuestionPartial(question) ? "warning" : "error"}>
                    {question.score}/{question.fullScore}分
                  </Tag>
                </Space>
              }
            >
              <div>
                <Paragraph style={{ marginBottom: 16 }}>
                  <Text strong>题目：</Text>
                  {question.question}
                </Paragraph>

                {question.options && renderOptions(question)}

                <AnswerSection>
                  <Text strong>您的答案：</Text>
                  <Text style={{ marginLeft: 8 }}>{renderUserAnswer(question)}</Text>
                </AnswerSection>

                <AnswerSection>
                  <Text strong>正确答案：</Text>
                  <Text style={{ marginLeft: 8, color: "#52c41a" }}>{renderCorrectAnswer(question)}</Text>
                </AnswerSection>

                <ExplanationSection>
                  <Space>
                    <RobotOutlined style={{ color: "#1890ff" }} />
                    <Text strong>答案解析：</Text>
                  </Space>
                  <Paragraph style={{ marginTop: 8, marginBottom: 0 }}>
                    {question.explanation}
                  </Paragraph>
                </ExplanationSection>

                {/* AI解析按钮 */}
                <div style={{ marginTop: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Space>
                    {!question.aiExplanation ? (
                          <Button
                        type="primary"
                        icon={<ThunderboltOutlined />}
                        loading={aiLoadingStates[question.id]}
                        onClick={() => handleGetAIExplanation(question.id, question)}
                      >
                        获取AI解析
                          </Button>
                    ) : (
                      <>
                        <Tag color="purple" icon={<BulbOutlined />}>
                          AI深度解析
                        </Tag>
                        <Button
                          type="default"
                          icon={<ReloadOutlined />}
                          loading={aiLoadingStates[question.id]}
                          onClick={() => handleGetAIExplanation(question.id, question, true)}
                          size="small"
                        >
                          重新生成
                        </Button>
                      </>
                    )}
                  </Space>
                </div>

                {/* AI解析内容 */}
                {question.aiExplanation && (
                  <AIExplanationSection>
                      <div style={{ whiteSpace: 'pre-line', lineHeight: '1.6' }}>
                        {question.aiExplanation}
                      </div>
                  </AIExplanationSection>
                )}
              </div>
            </QuestionCard>
          )}
        />
      </div>
        </>
      ) : (
        <div style={{ textAlign: "center", padding: "40px" }}>
          <Text type="secondary">暂无考试详情数据</Text>
        </div>
      )}
    </StyledModal>
  );
};

export default ExamDetailModal; 